<template>
	<div class="bgBox">
		<div class="cardBox" v-if="showCard">
			<div class="container">
				<div class="card">
					<div class="userinfo" v-if="avatarUrl">
						<div class="imgBox"><u--image :src="avatarUrl" shape="circle" width="40" height="40"></u--image></div>
						<div class="nickname">{{ nickName }} <small v-if="mysuit >= 0">您的位置为{{Math.floor(mysuit / peopleNums) + 1}}组</small></div>
					</div>
					<h3>{{ zhuti }}</h3>
					<p>{{ cyrs.length }}/{{ val.zw.length }}人已经参与</p>
					
				</div>
				
				<div class="yyBox">
					<div class="btns" v-if="mysuit == -1">
						<div class="btn" v-if="!yymy" @click="make()">参与排序</div>
						<div class="btn disable" v-else>预约满员</div>
					</div>
					
					<image v-if="mysuit != -1 && jsimg != ''" class="jsimg" :src="jsimg" mode="widthFix" @click="showImg(jsimg)"></image>
					
					<small v-if="mysuit >= 0">您的位置为{{ Math.floor(mysuit / peopleNums) + 1 }}组</small>
				</div>
				
			</div>
			
		</div>
		<div style="height: 80px;"></div>
		<div class="fixBottom">
			<div class="my">
				<u-button  text="我的参与" type="info" size="large" @click="toMy()"></u-button>
			</div>
			<div class="btns">
				<u-button openType="share" text="分享排序" type="warning" size="large"></u-button>
			</div>
			
		</div>
		<u-toast ref="uToast"></u-toast>
	</div>
</template>

<script>
const db = wx.cloud.database();
export default {
	name: 'headcomd',
	data() {
		return {
			wyz: '',
			avatarUrl: '',
			nickName: '',
			openid: '',
			zhuti: '',
			n: 2,
			val: {},
			cyrs: [],
			showCard: false,
			mysuit: -1,
			yymy: false,
			peopleNums: 2,
			jsimg: ""
		};
	},
	onShareAppMessage(options) {
		let that = this
		let shareObj = {
		    title: that.zhuti,
		    path: 'pages/huodong/paizuo/fenzu_join?wyz=' + that.wyz,
		    imageUrl: ''   
		};
		return shareObj
	},
	onShareTimeline(res) {
		let that = this;
		return {
			title: that.zhuti,
			query: "wyz=" + that.wyz
		};
	},
	onLoad(options) {
		if (!options) {
			this.infoScene = 'default';
		} else {
			this.wyz = options.wyz;
		}
	},
	computed: {},
	mounted() {
		this.getPageInfo();
		
	},
	watch: {},
	created() {
		let that = this;
		var openid = wx.getStorageSync('useropenid');
		var user_ava_nick = wx.getStorageSync('user_ava_nick');
		if(user_ava_nick){
			that.avatarUrl = user_ava_nick.avatarUrl
			that.nickName = user_ava_nick.nickName
		}
		if (openid) {
			that.openid = openid;
		} else {
			that.getopenid();
		}
	},
	methods: {
		getopenid() {
			let that = this;
			wx.cloud.callFunction({
				name: 'getopenid',
				data: {},
				complete: res => {
					that.saveOpenid(res.result.openid);
					that.openid = res.result.openid
					wx.setStorageSync('useropenid', res.result.openid);
				}
			});
		},
		saveOpenid(openid) {
			db.collection('user_info')
				.where({
					openid: openid
				})
				.get({
					success: function(res) {
						if (res.data.length == 0) {
							db.collection('user_info').add({
								data: {
									openid: openid,
									time: new Date()
								},
								success: function(res) {
									console.log('openid储存成功' + openid);
								}
							});
						}
					}
				});
		},
		getPageInfo() {
			let that = this;
			db.collection('paixu_fenzu')
				.where({
					wyz: that.wyz
				})
				.get({
					success: function(res) {
						if (res.data.length >= 0) {
							that.zhuti = res.data[0].zhuti;
							that.val = res.data[0];
							that.jsimg = res.data[0].jsimg;
							that.filterYh(that.val);
						}
					}
				});
		},
		filterYh(v) {
			let that = this;
			that.cyrs = v.zw.filter(item => item.openid != null);
			if(that.cyrs.length == that.val.nums){
				that.yymy = true
			}
			that.showCard = true;
			this.checkCy()
			// this.getImg()
		},
		getImg(){
			let that = this
			wx.cloud.getTempFileURL({
				fileList: [{
					fileID: that.val.jsimg
				}]
			}).then(res => {
				that.jsimg = res.fileList[0].tempFileURL
			}).catch(error => {
			  // handle error
			})
		},
		make() {
			let that = this
			// if(!that.avatarUrl){
			// 	that.getUserProfile()
			// 	return
			// }
			if(that.mysuit != -1){
				that.showToast('error','您已占座')
				return
			}
			wx.showLoading()
			
			that.updateZw()
		},
		getRandom(length){
			return Math.floor(Math.random() * length)
		},
		updateZw(){
			let that = this
			db.collection('paixu_fenzu').where({
				wyz: that.wyz
			}).get({
				success: function(res) {
					console.log(res)
					if (res.data.length > 0) {
						let allzw = res.data[0].zw;
						let z = []
						allzw.filter((item,index) => {
							if(item.openid == null){
								z.push(index)
							}
						})
						let ran = z[that.getRandom(z.length)]
						that.checkPeople(ran)
						
					}
				}
			})
		},
		updatePeople(ran){
			let that = this
			db.collection('paixu_fenzu').where({
				wyz: that.wyz,
				'zw.id': ran
			}).update({
				data: {
					'zw.$.openid': that.openid,
					'zw.$.change': true
				},
				success: function(res){
					that.showToast("success","占座成功")
					wx.hideLoading()
					that.saveCy()
				}
			})
		},
		checkPeople(ran){
			let that = this
			db.collection('paixu_fenzu').where({
				wyz: that.wyz
			}).get({
				success:function(res){
					let allzw = res.data[0].zw;
					console.log(allzw[ran].change)
					if(allzw[ran].change == false){
						that.updatePeople(ran)
					}else{
						that.getPageInfo()
						that.updateZw()
					}
				}
			})
		},
		saveCy(){
			let that = this
			db.collection('paixu_danpai_cyyh').where({
				openid: that.openid
			}).get({
				success: function(res) {
					if (res.data.length > 0) {
						let c = res.data[0].cyhd
						c.push({zhuti: that.zhuti,wyz: that.wyz,hd: "fenzu_join"})
						db.collection('paixu_danpai_cyyh').where({
							openid: that.openid
						}).update({
							data: {
								cyhd: c
							},
							success: function(res){
								that.getPageInfo();
							}
						})
					}else{
						let hd = [
							{zhuti: that.zhuti,wyz: that.wyz,hd: "fenzu_join"}
						]
						db.collection('paixu_danpai_cyyh').add({
							data: {
								openid: that.openid,
								cyhd: hd,
								time: new Date()
							},
							success: function(res) {
								that.getPageInfo();
							},
							fail: function(req){
								console.log(req)
							}
						});
					}
				}
			})
		},
		showToast(type, info) {
			this.$refs.uToast.show({
				type: type,
				icon: false,
				title: '失败主题',
				message: info
			});
		},
		getUserProfile(e) {
			// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			wx.getUserProfile({
				desc: '用于保存用户的昵称', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: res => {
					this.userInfo = res.userInfo
					wx.setStorage({
						key: 'user_ava_nick', //本地缓存中指定的 key(类型：string)
						data: res.userInfo, //需要存储的内容。只支持原生类型、Date、及能够通过JSON.stringify序列化的对象(类型:any)
						success: s => {
							this.avatarUrl = res.userInfo.avatarUrl,
							this.nickName = res.userInfo.nickName
							this.make()
						},
						fail: f => {
							//  console.log('存储缓存失败====',f);
						}
					});
				}
			});
		},
		checkCy(){
			let that = this
			let cyrs = that.val.zw
			let isCy = false
			
			that.peopleNums = that.val.nums / that.val.zu
			
			cyrs.filter((item,index) => {
				if(item){
					if(item.openid == that.openid){
						isCy = true
						that.mysuit = index
						return
					}
				}
			})
		},
		toMy(){
			let that = this
			uni.navigateTo({
				url: "./my"
			})
		},
		showImg(img){
			wx.previewImage({
				urls: [img], //需要预览的图片http链接列表，注意是数组
				current: '', // 当前显示图片的http链接，默认是第一个
				success: function(res) {},
				fail: function(res) {},
				complete: function(res) {}
			});
		}
	}
};
</script>

<style>
@import url(./index.css);
</style>
